//
//  EXTool.swift
//  FastDevelop
//
//  Created by IOS1 on 2025/6/23.
//

import Foundation
import UIKit

//MARK: ============ Date ============
enum DateFormat: String {
    // 年-月-日 时-分-秒
    case yearMonthDayHourMinuteSecond       = "yyyy-MM-dd HH:mm:ss"
    // 年-月-日 时-分
    case yearMonthDayHourMinute             = "yyyy-MM-dd HH:mm"
    // 年-月-日 时
    case yearMonthDayHour                   = "yyyy-MM-dd HH"
    // 年-月-日
    case yearMonthDay                       = "yyyy-MM-dd"
    // 年-月-日
    case yearMonth                          = "yyyy-MM"
    // 年
    case year                               = "yyyy"
    
    // 月-日 时-分-秒
    case MonthDayHourMinuteSecond           = "MM-dd HH:mm:ss"
    // 月-日 时-分
    case MonthDayHourMinute                 = "MM-dd HH:mm"
    // 月-日 时
    case MonthDayHour                       = "MM-dd HH"
    // 月-日
    case MonthDay                           = "MM-dd"
    // 月
    case Month                              = "MM"
    
    // 日
    case Day                                = "dd"
    
    // 时-分-秒
    case HourMinuteSecond                   = "HH:mm:ss"
    // 时-分
    case HourMinute                         = "HH:mm"
    // 时
    case Hour                               = "HH"
    
}

extension Date {
    
    //TODO: - 日期转字符串
    func toString(_ format: DateFormat = .yearMonthDay) -> String {
        toString(format.rawValue)
    }
    
    //TODO: - 日期转字符串
    func toString(_ format: String) -> String {
        let formatter = DateFormatter.init()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
    
    //TODO: - Date 转 时间戳 (毫秒)
    func toTimeStamp() -> Int {
        let timeInterval: TimeInterval = self.timeIntervalSince1970
        let timeStamp = CLongLong(round(timeInterval*1000))
        return Int(timeStamp)
    }
    
}

extension Date {
    func formattedCalendarDate() -> String {
        let calendar = Calendar.current
        let now = Date()
        
        if calendar.isDate(self, inSameDayAs: now) {
            return formatDate(prefix: "Today")
        } else {
            let weekday = calendar.component(.weekday, from: self)
            let weekdayName = calendar.weekdaySymbols[weekday - 1]
            return formatDate(prefix: weekdayName)
        }
    }
    
    private func formatDate(prefix: String) -> String {
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "en_US") // 可选：强制英文
        formatter.dateFormat = "MMMM d'\(daySuffix())', yyyy"
        return "\(prefix), \(formatter.string(from: self))"
    }
    
    private func daySuffix() -> String {
        let day = Calendar.current.component(.day, from: self)
        switch day {
        case 1, 21, 31: return "st"
        case 2, 22: return "nd"
        case 3, 23: return "rd"
        default: return "th"
        }
    }
}

//MARK: ============ Color ============
extension UIColor {
    
    convenience init(hex: Int, alpha: CGFloat = 1.0) {
        let r = CGFloat((hex & 0xFF0000) >> 16) / 255.0
        let g = CGFloat((hex & 0x00FF00) >> 8) / 255.0
        let b = CGFloat(hex & 0x0000FF) / 255.0
        self.init(red: r, green: g, blue: b, alpha: alpha)
    }
    
    convenience init(hexString str: String, alpha: CGFloat = 1.0) {
        let range = NSMakeRange(0, str.count)
        let hexString = (str as NSString).replacingOccurrences(of: "[^0-9a-fA-F]", with: "", options: .regularExpression, range: range)
        let hex = Int(hexString, radix: 16).require(hint: "Please check the hexString")
        self.init(hex: hex, alpha: alpha)
    }
    
    static var random: UIColor {
        get {
            let red = CGFloat(arc4random()%256)/255.0
            let green = CGFloat(arc4random()%256)/255.0
            let blue = CGFloat(arc4random()%256)/255.0
            return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        }
    }
}

extension UIColor {
    static let bg = UIColor(hexString: "#14161A")
    static let theme_blue = UIColor(hexString: "#4549E0")
}


extension Optional {
    
    /// 强制要求这个 optional 不为空
    ///
    /// 这个方法返回 optional 的值，或者在optional 为空的时候触发 error
    ///
    ///
    /// - Parameters:
    ///   - hint: 为空抛出的错误信息
    ///
    /// - Returns: optional 的值.
    func require(hint hintExpression: @autoclosure() -> String? = nil,
                 file: StaticString = #file,
                 line: UInt = #line) -> Wrapped {
        guard let unwrapped = self else {
            var message = "required value was nil \(file), at line \(line)"
            if let hint = hintExpression() {
                message.append(". Debugging hit: \(hint)")
            }
#if !os(Linux)
            let exception = NSException(name: .invalidArgumentException,
                                        reason: message,
                                        userInfo: nil)
            exception.raise()
#endif
            
            preconditionFailure(message)
        }
        return unwrapped
    }
}

//MARK: ============ UIView ============
extension UIView {
    func addSubviews(_ subviews: [UIView]) {
        subviews.forEach { addSubview($0) }
    }
    
    /// 设置视图的指定角的圆角
    /// - Parameters:
    ///   - corners: 需要设置圆角的角。可以使用 [.topLeft, .topRight, .bottomLeft, .bottomRight]
    ///   - radius: 圆角的半径
    func setCornerRadius(corners: UIRectCorner, radius: CGFloat) {
        DispatchQueue.main.async {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            self.layer.mask = mask
        }
    }
}


//MARK: ============ CGFloat ============
extension CGFloat {
    
    /// 状态栏高度
    static var statusHeight: Double {
        if #available(iOS 13.0, *) {
            let manager = UIApplication.shared.windows.first?.windowScene?.statusBarManager
            return Double(manager?.statusBarFrame.size.height ?? 20.0)
        } else {
            return UIApplication.shared.statusBarFrame.size.height
        }
    }
    
    /// 屏幕宽
    static let screenWidth = UIScreen.main.bounds.size.width
    /// 屏幕高
    static let screenHeight = UIScreen.main.bounds.size.height
    /// 是否为刘海屏
    static let isIPhoneX: Bool          = statusHeight >= 44.0
    /// 底部安全间距
    static let safe_bottom              = isIPhoneX ? 34.0 : 0
    /// 导航栏高度
    static let navi_height              = statusHeight + 44.0
    /// Tabbar 高度
    static let tabBar_height            = safe_bottom + 49.0
    /// 底部推荐距离
    static let bottomSpace              = isIPhoneX ? 34.0 : 20.0
    
}


//MARK: ============ String ============
extension String {
    
    //是否为邮箱
    var isValidEmail: Bool {
        // http://emailregex.com/
        let regex = "^(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$"
        return range(of: regex, options: .regularExpression, range: nil, locale: nil) != nil
    }
    
    var isValidatePwd: Bool{
        if self.count == 0 {
            return false
        }
        guard self.count >= 6,self.count <= 16 else {
            return false
        }
        return true
    }
}


//MARK: ============ UIApplication ============
extension UIApplication {
    
    /// 获取 Window
    class var window: UIWindow? {
        get {
            if let appDelegate = UIApplication.shared.delegate,
               let lendo_window = appDelegate.window {
                return lendo_window
            }
            return UIApplication.shared.keyWindow
        }
    }
    
}

//MARK: - UITableView
extension UITableView {
    
    //TODO: - register
    func register(nib cells: UITableViewCell.Type..., in bundle: Bundle? = .main) {
        cells.forEach({ register(UINib(nibName: String(describing: $0), bundle: bundle), forCellReuseIdentifier: String(describing: $0)) })
    }
    
    func register(_ cells: UITableViewCell.Type...) {
        cells.forEach({ register($0.self, forCellReuseIdentifier: String(describing: $0)) })
    }
    
    //TODO: -
    func cell<T: UITableViewCell>(_ type: T.Type, indexPath: IndexPath) -> T {
        guard let _ = dequeueReusableCell(withIdentifier: String(describing: type)) else {
            register(type)
            return cell(type, indexPath: indexPath)
        }
        guard let cell = dequeueReusableCell(withIdentifier: String(describing: type), for: indexPath) as? T else {
            fatalError(
                "没有注册此Cell: \(String(describing: type))")
        }
        return cell
    }
    
}
